package com.example.myapplication.music;


import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;

import java.util.Timer;
import java.util.TimerTask;

public class MusicService extends Service {
    private Timer timer;
    private MediaPlayer player;
    public MusicService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
      return new  MusicControl();
    }

    public void addTimer(){
        if(timer==null){
            timer=new Timer();
        TimerTask timerTask=new TimerTask() {
            @Override
            public void run() {
                if(player==null) return;
                int duration= player.getDuration();
                int currentPosition= player.getCurrentPosition();

                Message msg= MusicActivity.handler.obtainMessage();//创建消息对象

                Bundle bundle=new Bundle();
                bundle.putInt("duration",duration);
                bundle.putInt("currentPosition",currentPosition);

                msg.setData(bundle);
                MusicActivity.handler.sendMessage(msg);

            }
        };
        timer.schedule(timerTask,5,500);
    }
    }
    class MusicControl extends Binder{
        private String packageName;
        public void play(int i){
            Uri uri=Uri.parse("android.resource://"+getPackageName()+"/raw/"+"music"+i);
            try{
                //重置音乐播放器
                player.reset();
                //加载多媒体文件
                player=MediaPlayer.create(getApplicationContext(),uri);
                player.start();//播放音乐
                addTimer();//添加计时器
            }catch(Exception e){
                e.printStackTrace();
        }
    }
        public void pausePlay(){
            player.pause();//暂停播放音乐
        }

        public void previous(){

        }

        public void continuePlay(){
            player.start();//继续播放音乐
        }
        public void seekTo(int progress){
            player.seekTo(progress);//设置音乐的播放位置
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(player==null)return;
        if(player.isPlaying())
            player.stop();
        player.release();
        player=null;
    }
}
